'use client';

import { useState } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Badge } from '@/components/ui/badge';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { formatDate, formatCurrency } from '@/lib/utils';
import { multiChainApi } from '@/lib/multi-chain-api';
import { useChain } from '@/context/ChainContext';
import { 
  Settings, 
  Plus, 
  History, 
  TrendingUp, 
  TrendingDown, 
  AlertCircle, 
  Check, 
  X,
  Calculator,
  BarChart3,
  Clock
} from 'lucide-react';
import { toast } from '@/hooks/use-toast';

interface ExchangeRate {
  id: string;
  rate: number;
  effective_from: string;
  effective_to?: string;
  set_by_admin: string;
  reason?: string;
  is_active: boolean;
  created_at: string;
}

interface ExchangeStatistics {
  total_dtvc_supply: number;
  total_dtv_exchanged: number;
  current_exchange_rate: number;
  users_with_dtvc: number;
  rate_effective_from?: string;
  rate_set_by: string;
  current_rate_id?: string;
}

interface RateValidation {
  is_valid: boolean;
  warnings: string[];
  current_rate?: number;
  new_rate: number;
  change_percentage?: number;
}

interface CalculationResult {
  success: boolean;
  dtvc_amount: number;
  dtv_amount: number;
  rate: number;
  rate_id?: string;
  effective_from?: string;
  error?: string;
}

export function ExchangeRateManager() {
  const { currentChain } = useChain();
  const queryClient = useQueryClient();
  const [showNewRateDialog, setShowNewRateDialog] = useState(false);
  const [showHistoryDialog, setShowHistoryDialog] = useState(false);
  const [showCalculatorDialog, setShowCalculatorDialog] = useState(false);
  const [newRate, setNewRate] = useState('');
  const [reason, setReason] = useState('');
  const [effectiveFrom, setEffectiveFrom] = useState('');
  const [calculatorDtvc, setCalculatorDtvc] = useState('');
  const [calculatorDtv, setCalculatorDtv] = useState('');

  // Fetch current exchange rate
  const { data: currentRate } = useQuery<ExchangeRate>({
    queryKey: ['current-exchange-rate', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/dtvc/admin/exchange-rates/current');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Fetch exchange rate history
  const { data: rateHistory } = useQuery<ExchangeRate[]>({
    queryKey: ['exchange-rate-history', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/dtvc/admin/exchange-rates');
      return response.data;
    },
    enabled: showHistoryDialog,
  });

  // Fetch exchange statistics
  const { data: statistics } = useQuery<ExchangeStatistics>({
    queryKey: ['exchange-statistics', currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get('/api/v1/dtvc/admin/exchange-rates/statistics');
      return response.data;
    },
    refetchInterval: 30000,
  });

  // Rate validation mutation
  const validateRateMutation = useMutation({
    mutationFn: async (rate: number): Promise<RateValidation> => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.post('/api/v1/dtvc/admin/exchange-rates/validate', {
        rate,
        reason
      });
      return response.data;
    },
  });

  // Set new rate mutation
  const setNewRateMutation = useMutation({
    mutationFn: async (rateData: { rate: number; reason?: string; effective_from?: string }) => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.post('/api/v1/dtvc/admin/exchange-rates', rateData);
      return response.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['current-exchange-rate'] });
      queryClient.invalidateQueries({ queryKey: ['exchange-rate-history'] });
      queryClient.invalidateQueries({ queryKey: ['exchange-statistics'] });
      queryClient.invalidateQueries({ queryKey: ['dtvc-stats'] });
      setShowNewRateDialog(false);
      setNewRate('');
      setReason('');
      setEffectiveFrom('');
      toast({
        title: "Exchange Rate Updated",
        description: "New exchange rate has been set successfully.",
      });
    },
    onError: (error: any) => {
      toast({
        title: "Error",
        description: error.response?.data?.detail || "Failed to set exchange rate",
        variant: "destructive",
      });
    },
  });

  // Calculate DTVC/DTV amounts
  const { data: dtvcToDtvResult } = useQuery<CalculationResult>({
    queryKey: ['calculate-dtv', calculatorDtvc, currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/dtvc/calculate/dtv?dtvc_amount=${calculatorDtvc}`);
      return response.data;
    },
    enabled: !!(calculatorDtvc && parseFloat(calculatorDtvc) > 0),
  });

  const { data: dtvToDtvcResult } = useQuery<CalculationResult>({
    queryKey: ['calculate-dtvc', calculatorDtv, currentChain],
    queryFn: async () => {
      const client = multiChainApi.getClient(currentChain);
      const response = await client.get(`/api/v1/dtvc/calculate/dtvc?dtv_amount=${calculatorDtv}`);
      return response.data;
    },
    enabled: !!(calculatorDtv && parseFloat(calculatorDtv) > 0),
  });

  const handleValidateRate = async () => {
    if (!newRate || parseFloat(newRate) <= 0) {
      toast({
        title: "Invalid Rate",
        description: "Please enter a valid positive rate",
        variant: "destructive",
      });
      return;
    }

    validateRateMutation.mutate(parseFloat(newRate));
  };

  const handleSetNewRate = async () => {
    if (!newRate || parseFloat(newRate) <= 0) {
      toast({
        title: "Invalid Rate",
        description: "Please enter a valid positive rate",
        variant: "destructive",
      });
      return;
    }

    const rateData: { rate: number; reason?: string; effective_from?: string } = {
      rate: parseFloat(newRate),
    };

    if (reason.trim()) {
      rateData.reason = reason.trim();
    }

    if (effectiveFrom) {
      rateData.effective_from = effectiveFrom;
    }

    setNewRateMutation.mutate(rateData);
  };

  const getRateChangeIndicator = (currentRate?: number, newRate?: number) => {
    if (!currentRate || !newRate) return null;
    
    const change = ((newRate - currentRate) / currentRate) * 100;
    const isIncrease = change > 0;
    
    return (
      <div className={`flex items-center gap-1 text-sm ${isIncrease ? 'text-green-600' : 'text-red-600'}`}>
        {isIncrease ? <TrendingUp className="h-3 w-3" /> : <TrendingDown className="h-3 w-3" />}
        {Math.abs(change).toFixed(1)}%
      </div>
    );
  };

  return (
    <div className="space-y-6">
      {/* Header with actions */}
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold">Exchange Rate Management</h2>
          <p className="text-muted-foreground">Manage DTVC to DTV conversion rates</p>
        </div>
        <div className="flex gap-2">
          <Dialog open={showCalculatorDialog} onOpenChange={setShowCalculatorDialog}>
            <DialogTrigger asChild>
              <Button variant="outline">
                <Calculator className="h-4 w-4 mr-2" />
                Calculator
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-md">
              <DialogHeader>
                <DialogTitle>Exchange Calculator</DialogTitle>
                <DialogDescription>
                  Calculate DTVC/DTV conversions using current rate
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="dtvc-amount">DTVC Amount</Label>
                  <Input
                    id="dtvc-amount"
                    type="number"
                    placeholder="Enter DTVC amount"
                    value={calculatorDtvc}
                    onChange={(e) => setCalculatorDtvc(e.target.value)}
                  />
                  {dtvcToDtvResult?.success && (
                    <p className="text-sm text-green-600 mt-1">
                      = {dtvcToDtvResult.dtv_amount} DTV
                    </p>
                  )}
                </div>
                <div>
                  <Label htmlFor="dtv-amount">DTV Amount</Label>
                  <Input
                    id="dtv-amount"
                    type="number"
                    placeholder="Enter DTV amount"
                    value={calculatorDtv}
                    onChange={(e) => setCalculatorDtv(e.target.value)}
                  />
                  {dtvToDtvcResult?.success && (
                    <p className="text-sm text-green-600 mt-1">
                      = {dtvToDtvcResult.dtvc_amount.toLocaleString()} DTVC
                    </p>
                  )}
                </div>
                {currentRate && (
                  <div className="bg-muted p-3 rounded">
                    <p className="text-sm">
                      <span className="font-medium">Current Rate:</span> {currentRate.rate} DTVC = 1 DTV
                    </p>
                  </div>
                )}
              </div>
            </DialogContent>
          </Dialog>

          <Dialog open={showHistoryDialog} onOpenChange={setShowHistoryDialog}>
            <DialogTrigger asChild>
              <Button variant="outline">
                <History className="h-4 w-4 mr-2" />
                History
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-4xl max-h-[80vh] overflow-y-auto">
              <DialogHeader>
                <DialogTitle>Exchange Rate History</DialogTitle>
                <DialogDescription>
                  Historical exchange rates and changes
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                {rateHistory?.map((rate) => (
                  <Card key={rate.id} className={rate.is_active ? 'border-green-500' : ''}>
                    <CardContent className="p-4">
                      <div className="flex items-center justify-between">
                        <div>
                          <div className="flex items-center gap-2">
                            <span className="text-lg font-bold">{rate.rate} DTVC = 1 DTV</span>
                            {rate.is_active && (
                              <Badge variant="success">Active</Badge>
                            )}
                          </div>
                          <p className="text-sm text-muted-foreground">
                            Set by: {rate.set_by_admin}
                          </p>
                          {rate.reason && (
                            <p className="text-sm mt-1">{rate.reason}</p>
                          )}
                        </div>
                        <div className="text-right text-sm">
                          <p>Effective: {formatDate(rate.effective_from)}</p>
                          {rate.effective_to && (
                            <p>Until: {formatDate(rate.effective_to)}</p>
                          )}
                          <p className="text-muted-foreground">
                            Created: {formatDate(rate.created_at)}
                          </p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                ))}
              </div>
            </DialogContent>
          </Dialog>

          <Dialog open={showNewRateDialog} onOpenChange={setShowNewRateDialog}>
            <DialogTrigger asChild>
              <Button>
                <Plus className="h-4 w-4 mr-2" />
                Set New Rate
              </Button>
            </DialogTrigger>
            <DialogContent>
              <DialogHeader>
                <DialogTitle>Set New Exchange Rate</DialogTitle>
                <DialogDescription>
                  Configure a new DTVC to DTV exchange rate
                </DialogDescription>
              </DialogHeader>
              <div className="space-y-4">
                <div>
                  <Label htmlFor="rate">Exchange Rate (DTVC = 1 DTV)</Label>
                  <Input
                    id="rate"
                    type="number"
                    placeholder="e.g., 1000"
                    value={newRate}
                    onChange={(e) => setNewRate(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    How many DTVC equals 1 DTV
                  </p>
                  {currentRate && newRate && (
                    <div className="flex items-center gap-2 mt-2">
                      <span className="text-sm">Change from current:</span>
                      {getRateChangeIndicator(currentRate.rate, parseFloat(newRate))}
                    </div>
                  )}
                </div>

                <div>
                  <Label htmlFor="reason">Reason (Optional)</Label>
                  <Textarea
                    id="reason"
                    placeholder="Reason for rate change..."
                    value={reason}
                    onChange={(e) => setReason(e.target.value)}
                    rows={3}
                  />
                </div>

                <div>
                  <Label htmlFor="effective-from">Effective From (Optional)</Label>
                  <Input
                    id="effective-from"
                    type="datetime-local"
                    value={effectiveFrom}
                    onChange={(e) => setEffectiveFrom(e.target.value)}
                  />
                  <p className="text-xs text-muted-foreground mt-1">
                    Leave empty to make effective immediately
                  </p>
                </div>

                {/* Rate validation results */}
                {validateRateMutation.data && (
                  <Alert className={validateRateMutation.data.is_valid ? 'border-green-500' : 'border-orange-500'}>
                    <AlertCircle className="h-4 w-4" />
                    <AlertDescription>
                      <div className="space-y-2">
                        <div className="flex items-center gap-2">
                          {validateRateMutation.data.is_valid ? (
                            <Check className="h-4 w-4 text-green-600" />
                          ) : (
                            <X className="h-4 w-4 text-red-600" />
                          )}
                          <span className="font-medium">
                            {validateRateMutation.data.is_valid ? 'Valid Rate' : 'Invalid Rate'}
                          </span>
                        </div>
                        {validateRateMutation.data.warnings.length > 0 && (
                          <ul className="text-sm space-y-1">
                            {validateRateMutation.data.warnings.map((warning, index) => (
                              <li key={index} className="text-orange-600">• {warning}</li>
                            ))}
                          </ul>
                        )}
                        {validateRateMutation.data.change_percentage && (
                          <p className="text-sm">
                            Change: {validateRateMutation.data.change_percentage.toFixed(1)}% from current rate
                          </p>
                        )}
                      </div>
                    </AlertDescription>
                  </Alert>
                )}

                <div className="flex gap-2">
                  <Button
                    variant="outline"
                    onClick={handleValidateRate}
                    disabled={!newRate || validateRateMutation.isPending}
                  >
                    Validate Rate
                  </Button>
                  <Button
                    onClick={handleSetNewRate}
                    disabled={!newRate || setNewRateMutation.isPending}
                  >
                    {setNewRateMutation.isPending ? 'Setting...' : 'Set Rate'}
                  </Button>
                </div>
              </div>
            </DialogContent>
          </Dialog>
        </div>
      </div>

      {/* Current Rate and Statistics Cards */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Current Exchange Rate</CardTitle>
            <Settings className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {currentRate ? `${currentRate.rate}` : 'Not Set'}
            </div>
            <p className="text-xs text-muted-foreground">DTVC = 1 DTV</p>
            {currentRate && (
              <div className="mt-2 space-y-1">
                <p className="text-xs text-muted-foreground">
                  <Clock className="h-3 w-3 inline mr-1" />
                  Effective: {formatDate(currentRate.effective_from)}
                </p>
                <Badge variant={currentRate.is_active ? "success" : "secondary"} className="text-xs">
                  {currentRate.is_active ? "Active" : "Inactive"}
                </Badge>
              </div>
            )}
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total DTVC Supply</CardTitle>
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">
              {statistics ? formatCurrency(statistics.total_dtvc_supply, 'DTVC') : '0'}
            </div>
            <p className="text-xs text-muted-foreground">Available for exchange</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Total DTV Exchanged</CardTitle>
            <TrendingUp className="h-4 w-4 text-blue-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-blue-600">
              {statistics ? formatCurrency(statistics.total_dtv_exchanged, 'DTV') : '0'}
            </div>
            <p className="text-xs text-muted-foreground">Lifetime exchanges</p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">Users with DTVC</CardTitle>
            <TrendingUp className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statistics?.users_with_dtvc || 0}
            </div>
            <p className="text-xs text-muted-foreground">Active holders</p>
          </CardContent>
        </Card>
      </div>

      {/* Current Rate Details */}
      {currentRate && (
        <Card>
          <CardHeader>
            <CardTitle>Current Rate Details</CardTitle>
            <CardDescription>Information about the active exchange rate</CardDescription>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
              <div>
                <Label className="text-sm font-medium text-muted-foreground">Rate</Label>
                <div className="text-xl font-bold">{currentRate.rate} DTVC = 1 DTV</div>
              </div>
              <div>
                <Label className="text-sm font-medium text-muted-foreground">Set By</Label>
                <div className="font-mono text-sm">{currentRate.set_by_admin}</div>
              </div>
              <div>
                <Label className="text-sm font-medium text-muted-foreground">Effective From</Label>
                <div className="text-sm">{formatDate(currentRate.effective_from)}</div>
              </div>
              {currentRate.reason && (
                <div className="md:col-span-2 lg:col-span-3">
                  <Label className="text-sm font-medium text-muted-foreground">Reason</Label>
                  <div className="text-sm">{currentRate.reason}</div>
                </div>
              )}
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  );
}